package com.g7.figmaapi.common.exception.handle;

import com.g7.figmaapi.common.exception.business.BusinessException;
import com.g7.figmaapi.common.exception.business.ValidationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常拦截
 *
 * @author taoxiangqian
 * @since 2023/10/26
 **/
@ControllerAdvice
public class GlobalExceptionHandler extends BaseGlobalExceptionHandler {

    /**
     * 500的异常会被这个方法捕获
     *
     * @param req 请求体
     * @param rsp 响应
     * @param e   异常
     * @return org.springframework.web.servlet.ModelAndView
     * @author taoxiangqian
     * @since 2023/10/26
     **/
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handleError(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception {
        return handleError(req, rsp, e, "", HttpStatus.OK);
    }

    /**
     * 验证异常
     * @param req
     * @param rsp
     * @param e
     * @return org.springframework.web.servlet.ModelAndView
     * @author taoxiangqian
     * @since 2023/10/26
     **/
    @ExceptionHandler(ValidationException.class)
    public ModelAndView handleValidationException(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception {
        return handleError(req, rsp, e, "", HttpStatus.OK);
    }

    /**
     * 业务并发送异常信息
     * @param req
     * @param rsp
     * @param e
     * @return org.springframework.web.servlet.ModelAndView
     * @author taoxiangqian
     * @since 2023/10/26
     **/
    @ExceptionHandler(BusinessException.class)
    public ModelAndView handleBusinessException(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception {
        return handleError(req, rsp, e, "", HttpStatus.OK);
    }

}
